import './assets/main.css'
import 'element-plus/dist/index.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'

import App from './App.vue'
import router from './router'
import { useAuthStore } from './stores/auth'

const app = createApp(App)

app.use(createPinia())
app.use(router)
app.use(ElementPlus)

// Initialize authentication state
const initializeApp = async () => {
  const authStore = useAuthStore()
  
  // Initialize auth state from storage
  authStore.initializeAuth()
  
  // If user has stored credentials, validate them
  if (authStore.token && authStore.user) {
    try {
      // Validate token by fetching current user info
      await authStore.getCurrentUser()
    } catch (error) {
      console.warn('Stored token is invalid, clearing auth state:', error)
      authStore.clearAuthState()
    }
  }
}

// Initialize app
initializeApp().then(() => {
  app.mount('#app')
}).catch((error) => {
  console.error('Failed to initialize app:', error)
  app.mount('#app')
})
